/*
@Time : 2020/4/28 0028 15:09
@Author : visons
*/
package message

import (
	"bytes"
	"crypto/sha1"
	"encoding/json"
	"errors"
	"fmt"
	"gopkg/logger"
	"io/ioutil"
	"net/http"
	"sort"
	"strings"
)

const SendURL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="

type ReceiveMsg struct {
	FromUserName string `json:"FromUserName,omitempty"` //发送者的openid
	ToUserName   string `json:"ToUserName,omitempty"`   //小程序的原始ID
	Content      string `json:"Content,omitempty"`      //文本消息内容
	CreateTime   int64  `json:"CreateTime,omitempty"`   // 	消息创建时间(整型）
	MsgId        int64  `json:"MsgId,omitempty"`        //消息类型
	MsgType      string `json:"MsgType,omitempty"`      //消息id，64位整型
	Event        string `json:"Event,omitempty"`
}

type ResponseMsg struct {
	ToUser          string           `json:"touser"`                    //用户的 OpenID
	MsgType         string           `json:"msgtype"`                   //消息类型
	Text            *Text            `json:"text,omitempty"`            //文本消息，msgtype="text" 时必填
	Image           *Image           `json:"image,omitempty"`           //图片消息，msgtype="image" 时必填
	Link            *Link            `json:"link,omitempty"`            //图文链接，msgtype="link" 时必填
	MiniProgramPage *MiniProgramPage `json:"miniprogrampage,omitempty"` //小程序卡片，msgtype="miniprogrampage" 时必填
}

type Text struct {
	Content string `json:"content,omitempty"`
}

type Image struct {
	MediaId string `json:"media_id"`
}

type Link struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Url         string `json:"url"`
	ThumbUrl    string `json:"thumb_url"`
}

type MiniProgramPage struct {
	Title        string `json:"title"`
	PagePath     string `json:"page_path"`
	ThumbMediaId string `json:"thumb_media_id"`
}

type SendMsgRes struct {
	ErrMsg  string `json:"errMsg"`
	ErrCode int64  `json:"errCode"`
}

func SendResponseMsg(accessToken string, res *ResponseMsg) error {
	data, err := json.Marshal(res)
	if err != nil {
		return errors.New(fmt.Sprintf("json marshal fail:%v", err))
	}
	resp, err := http.Post(SendURL+accessToken, "application/json;charset=utf-8", bytes.NewReader(data))
	defer resp.Body.Close()
	if err != nil {
		return errors.New(fmt.Sprintf("send msg fail:%v", err))
	}
	body, err := ioutil.ReadAll(resp.Body)

	logger.Info("send msg response:%s", string(body))
}

func CheckSignature(signature, token, timestamp, nonce string) bool {
	tmpArr := []string{token, timestamp, nonce}
	sort.Strings(tmpArr)
	tmpStr := strings.Join(tmpArr, "")
	tmpStr = SHA1Str(tmpStr)
	if tmpStr == signature {
		return true
	} else {
		return false
	}
}

//sha1签名
func SHA1Str(str string) string {
	h := sha1.New()
	h.Write([]byte(str))
	bs := h.Sum(nil)
	sha1Str := fmt.Sprintf("%x", bs)
	return sha1Str
}
